package github.ziwukun.jsonql.lang;

import java.io.Serializable;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 属性排序选项
 * @author Hugo.Yu
 */
public class PropSortImpl implements PropSort{
	private static final long serialVersionUID = -4939185376063767519L;
	String prop;
	Serializable val;
	
	PropSortImpl(String prop,Serializable val){
		this.prop = prop;
		this.val = ObjectUtil.cloneByStream(val);
		
		asserts();
	}

	@Override
	public String prop() {
		return prop;
	}

	@Override
	public boolean valIsSort() {
		return val instanceof Sort;
	}

	@Override
	public boolean valIsSymbol() {
		return val instanceof SortSym;
	}

	@Override
	public Sort valAsSort() {
		if(!valIsSort()) {
			throw new RuntimeException("值类型不是Sort");
		}
		
		return ObjectUtil.cloneByStream((Sort)val);
	}
	
	@Override
	public SortSym valAsSym() {
		if(!valIsSymbol()) {
			throw new RuntimeException("值类型不是SortSym");
		}
		
		return (SortSym)val;
	}
	
	@Override
	public PropSort repProp(String propName) {
		
		return new PropSortImpl(propName, this.val);
	}

	@Override
	public PropSort repVal(Serializable val) {
		return new PropSortImpl(this.prop, val);
	}
	
	@Override
	public String toJSONQL() {
		return PropSortJson.writeJson(this);
	}
	
	private void asserts() {
		if(StrUtil.isBlank(prop)) {
			throw new JSONQLBuildException("属性名称不能为空字符串");
		}
		if(val == null) {
			throw new JSONQLBuildException("值不能为空");
		}
		if(!(val instanceof Sort) && !(val instanceof SortSym)) {
			throw new JSONQLBuildException("值类型只能是Sort | SortSym");
		}
		if(val instanceof Sort) {
			Sort sortVal = (Sort)val;
			if(sortVal.isEmpty()) {
				throw new JSONQLBuildException("值类型是Sort时，排序列表不能为空");
			}
		}
	}
}
